<template>
  <div>
    <h1>{{ id ? "编辑" : "新建" }}文章</h1>

    <div style="margin: 20px;"></div>

    <el-form @submit.native.prevent="save" label-width="120px">
      <el-form-item label="所属分类">
        <el-select v-model="model.catecories" multiple>
          <el-option 
          v-for="item in categories" 
          :key="item._id" 
          :label="item.name" 
          :value="item._id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标题">
        <el-input v-model="model.title"></el-input>
      </el-form-item>
      <el-form-item label="详情">
        <vue-editor useCustomImageHandler @imageAdded="handleImageAdded" v-model="model.body"></vue-editor>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" native-type="submit">保存</el-button>
      </el-form-item>
      </el-form>
  </div>
</template>



<script>
import { VueEditor } from "vue2-editor";
export default {
  name: "",
  props: {
    id: {}
  },
  components: {
    VueEditor
  },
  data() {
    return {
      model: {

      },
      categories:[],
    };
  },
  methods: {
    async handleImageAdded(file, Editor, cursorLocation, resetUploader) {
      // An example of using FormData
      // NOTE: Your key could be different such as:
      // formData.append('file', file)
 
      const formData = new FormData();
      formData.append("file", file);
 
      const res = await this.$http.post('upload',formData)
      Editor.insertEmbed(cursorLocation, "image", res.data.url);
      resetUploader();
      
    },
    async save() {
      //  新建和修改分类
      let res;
      if (this.id) {
        // 修改
        res = await this.$http.put(`rest/articles/${this.id}`, this.model);
      } else {
        // 新建
        // 提交数据请求不到最新数据的原因是存储数据是是异步操作（深坑）
        res = await this.$http.post("rest/articles", this.model);
      }
      //console.log(this.$http.get('rest/categories'))
        // console.log(await this.$http.get('rest/categories'))

      this.$router.push(`/articles/list`);
      // 有问题
      // 问题：
      //提交数据改变时，并没有同步存储，而是异步存储，使得第二次获取数据只能获取在此之前的数据
      //解决方案
      // 给提交数据的方法使用 async await  的方式，在提交数据的请求前加上await
      this.$message({
        type: "success",
        message: "保存成功"
      });
        // console.log(res)

    },
    async getdata(){
      await this.$http.get('rest/articles')
    },
    async fetch() {
      // 更新数据
      const res = await this.$http.get(`rest/articles/${this.id}`);
      this.model = res.data;
    },
    async fetchCategories() {
      // 获取父级分类
      const res = await this.$http.get(`rest/categories`);
      this.categories = res.data;
    }
  },
  created() {
    this.fetchCategories();
    this.id && this.fetch();
  }
};
</script>





<style lang="" scoped>

</style>